package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.vo.IotMsgNotifyData;
import com.zzyl.nursing.vo.IotMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设备数据Service业务层处理
 *
 * @author alexis
 * @date 2025-03-08
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 批量保存数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    @Transactional
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, deviceId));
        if (ObjectUtil.isNull(device)) {
            log.error("设备不存在,IotId:{}", deviceId);
            return;
        }
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        ArrayList<DeviceData> deviceDataList = new ArrayList<>();
        services.forEach(item -> {
            String eventTimeStr = item.getEventTime();
            LocalDateTime activeTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime alarmTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            item.getProperties().forEach((v, k) -> {
                DeviceData deviceData = DeviceData.builder().deviceName(device.getDeviceName())
                        .iotId(deviceId)
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(v)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .dataValue(k.toString())
                        .alarmTime(alarmTime)
                        .build();
                deviceDataList.add(deviceData);
            });
        });
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, deviceDataList);
        this.saveBatch(deviceDataList);
    }

    @Override
    public TableDataInfo<DeviceData> selectDeviceDataPageReq(DeviceDataPageReqDto dto) {
        Page<DeviceData> devicePage = new Page<>(dto.getPageNum(), dto.getPageSize());
        this.lambdaQuery().eq(DeviceData::getDeviceName, dto.getDeviceName())
                .eq(DeviceData::getFunctionId, dto.getFunctionId())
                .between(DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .page(devicePage);
        TableDataInfo<DeviceData> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setTotal(devicePage.getTotal());
        tableDataInfo.setRows(devicePage.getRecords());
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        return tableDataInfo;
    }
}
